import glossary from "../util/glossary"
import pattern_util from "./getSearchPattern"
import searchSchema from "../models/searchModel"
// query的对应三个字段的类型 从searchType_searchContent_searchTime
export default class SearchByTime {
  choose(req,res){
    let {searchContent, searchTime,keyword,pageNum,pageSize} = req.query;
    let reg_pattern = new pattern_util();
    let time_pattern = reg_pattern.getTimePattern(searchTime);
    if(time_pattern=="none"){
      res.status(500).send({data:{},msg:glossary.badRequest})
      return;
    }
    let reg = reg_pattern.getKeywordSegmentReg(keyword)
    reg = RegExp(reg)
    let condition = reg_pattern.getSearchCondition(searchContent,reg);
    time_pattern = RegExp(time_pattern)
    if(condition.length==0){
      res.status(500).send({data:{},msg:glossary.badRequest})
      return;
    }
    searchSchema.count({$and:[{date:time_pattern},{$or:condition}]},(err,count)=>{
      if(err){
        res.status(500).send({data:{},msg:glossary.internalError})
      }else{
        searchSchema.find({$and:[{date:time_pattern},{$or:condition}]}).sort({date:-1}).skip((pageNum-1)*pageSize).limit(parseInt(pageSize)).exec((err,doc)=>{
          if(err){
            res.json({data:{},msg:glossary.internalError})
          }else{
            res.json({data:{result:doc,total:count},msg:glossary.success})
          }
        })
      }
    })
  }
}
